//
//  ImageDownLoader.m
//  WeiboSpace
//
//  Created by  linan4 on 12-3-9.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ImageDLoader.h"
#import "XImageCache.h"

@implementation ImageDLoader
@synthesize orginUrl;
@synthesize _delegate;
-(id)init
{
	self = [super init];
	if(self)
	{
		result = [[NSMutableData alloc] init];
	}
	return self;
}

-(void)dealloc
{
	_delegate = nil;
	[result release];
	[connection release];
    self.orginUrl = nil;
	[super dealloc];
}

- (void)getImageFromURL:(NSString*)imageURL delegate:(NSObject <ImageDLoaderDelegate>*)newDelegate
{
	if([imageURL length] == 0)
		return;
		
    _delegate = newDelegate;
    self.orginUrl = imageURL;
    //看XImageCache中有没有
    if([[XImageCache shareXImageCache] dataForUrl:imageURL])
    {
        //NSLog(@"image from cache.");
        NSData *imageData = [[XImageCache shareXImageCache] dataForUrl:imageURL];
        if(_delegate != nil && [_delegate respondsToSelector:@selector(receivedImage: sender:)])
            [_delegate receivedImage:imageData sender:self];

        //可能需要跨线程。。。。
        return;
    }
    
	[self retain];
	
	NSURL *finalURL = [NSURL URLWithString:imageURL];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:finalURL];
	
	connection = [[NSURLConnection alloc] initWithRequest:theRequest 
													  delegate:self 
											  startImmediately:YES];
	if (!connection) 
	{
		[newDelegate receivedImage:nil sender:self];
		[self release];
	}

	
}

-(void)cancel
{
    _delegate = nil;
    [connection cancel];
    [self release];
}
#pragma mark NSURLConnection delegate methods


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	//连接后初始化为0
    [result setLength:0];
}


- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	//append 数据
    [result appendData:data];
}


- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[_delegate receivedImage:nil sender:self];
	[self release];

}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
//	if (imageView != nil) {
//		UIImage *imageCtl = [UIImage imageWithData:result];
//		[imageView setImage:imageCtl];
//	}
    
     //NSLog(@"image downloaded,url=%@",self.orginUrl);
    
    [[XImageCache shareXImageCache]setData:orginUrl image:result];
	//成功返回
    if(_delegate != nil && [_delegate respondsToSelector:@selector(receivedImage: sender:)])
        [_delegate receivedImage:result sender:self];
	
	[self release];
}

@end
